<?php
namespace Interfaces;

use think\Controller;
use think\Cookie;
use app\user\model\User;
use Exceptions\DataErrorException;

class BaseController extends Controller {
	protected $userDataCache = null;
	
	public function _initialize(){
		$this->assign('main', $this);
	}

	public function __get($key){
		switch($key){
			case 'userData': case 'user':
				return $this->getUserData();
		}
	}

	public function getUserData(){
		if($this->userDataCache === null){
			$loginToken = Cookie::get('login');
			try {
				if($loginToken && strlen($loginToken) > 0){
					//开始进行登录校验
					$this->userDataCache = User::getByToken($loginToken);
				} else {
					throw new DataErrorException();
				}
			} catch(DataErrorException $e){
				$this->userDataCache = User::getGuest();
			}
			return $this->userDataCache;
		} else {
			return $this->userDataCache;
		}
	}
}